declare const uni: any;

// 基础请求路径
const BASE_URL = 'http://localhost:9092/wx'

interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: Record<string, string>;
}

interface ResponseData<T = any> {
  code: number;
  msg: string;
  result: T;
}

// 封装请求方法
export const request = <T = any>(options: RequestOptions): Promise<ResponseData<T>> => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'content-type': 'application/json',
        ...options.header
      },
      success: (res: any) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(new Error(res.data.msg || '请求失败'))
        }
      },
      fail: (err: any) => {
        reject(err)
      }
    })
  })
}

// 封装常用请求方法
const http = {
  get(url, params = {}) {
    return request({
      url,
      method: 'GET',
      data: params
    })
  },

  post(url, data = {}) {
    return request({
      url,
      method: 'POST',
      data
    })
  },

  put(url, data = {}) {
    return request({
      url,
      method: 'PUT',
      data
    })
  },

  delete(url, data = {}) {
    return request({
      url,
      method: 'DELETE',
      data
    })
  }
}

export default http 